// 页面加载初始化方法
$(function () {
	var url = location.search; // 获取url中"?"符后的字串
	path = location.host; // ip地址
	currentTaskCompleteBool = false;// 当前是测试或者回放，true回放，false测试
	currentTaskState = 0;//记录当前任务的状态，0未开始，1进行中 ，2完成，3异常结束
	taskStatusBool = false;// 是否更新任务状态
	taskStartTime = "";// 开始测试时间
	taskEndTime = "";// 结束测试时间
	sendTime = "";// websocket请求是发送的时间
	//当前语音的编号
	currentVoiceNum = 0;
	//记录当前播放语音编号,为了实现播放一次的语音的之间添加一秒间隔
	currentVoiceNumCopy = 0;
	//记录当前音效播放次数
	currentPlayTimes = 0;
	//记录当前音效信息
	currentVoiceData = null;
	var dmiVoice = "";//图片+语音
	var pic = "";//图片信息
	var voice = "";//当前语音对象
	var testAllLog = null;//websocket返回的所有的日志信息
	if (url.indexOf("?") != -1) {
		var str = url.substr(1);
		strs = str.split("&");
		var taskNum = strs[0].split("=");
		testTaskId = taskNum[1];
		var nameNum = strs[1].split("=");
		userName = nameNum[1];
		if(strs[2]){
			currentTaskCompleteBool =(strs[2].split("=")[1] ==="false") ? false : true; 
		}
		if(strs[3]){
			taskStartTime =(strs[3].split("=")[1]).replace(/%20/," ");
			sendTime = taskStartTime;
		}
		if(strs[4]){
			taskEndTime =(strs[4].split("=")[1]).replace(/%20/," ");
		}
	}
	systemLastTime = '';
	getAllDataWebSocket = "";
	initProcess(); // 进度条复位函数
	initTestTask(testTaskId);

	getDmiDataWebSocket = "";
	querySequenceArray = []; // 展示测试序列中的测试用例
	currentSequenceList = []; // 测试序列的数据数组
	allCompleteBool = false; // 是否完成所有测试序列
	allSequenceArray = [];// 所有序列相同平台合并后的信息
	startBtnClickBool = false;// 开始测试按钮点击
	allSequenceComIndex = [];// 不同平台的序列已经测试的索引
	selectIndex = 0;// 当前点击的序列索引
	if(currentTaskCompleteBool){
		$('#startCHHF').html("开始回放");
		$('#stopTask').html("终止回放");
	}else{
		$('#startCHHF').html("申请平台");
		$('#versionBtn').css('display','none');
	}
	$('#stopTask').attr('disabled','true');
	// 获取lkj的初始数据
	var content=[{ID:"1",SYS_NAME:"LKJ软件版本"},{ID:"4",SYS_NAME:"ASTS软件版本"}];
	// 根据父节点ID获取当前软件版本下都有哪些类型的软件
	versionTypesName = getVersionTypesName(content[0].ID);
	// 当前被选中的版本号
	selectCases = [];
	// 测试序列的id数组
	taskIdArray = [];
	// 记录查看版本选中的第几个平台
	selectVersionIndex = 0;
	// 当前是否有可用平台
	currentPPlatformBool = true;
	// 当前无可用平台的提示信息
	currentPStr = "";
	// 是否可以开始测试
	startTestBool = false;
	//测试进行中时，根据当前测试的控件，自动向上滚动到当前控件位置
	testingScrollY = 0;
	//记录当前任务的状态，2：暂停，3：继续
	testTaskState = 0;
	
	window.onbeforeunload=function(){
		// 当任务为测试时，终止测试后，退出时释放平台
		if(!currentTaskCompleteBool){
			for(var i = 0;i<allSequenceArray.length;i++){
				resetPlatformEdit(allSequenceArray[i][0].PLATFORM_ID);
			}
			//刷新退出时如果当前任务为进行中状态时，重置任务状态为异常结束
			if(currentTaskState == 1){
				setTaskState(3);
			}
			//刷新退出时发送停止脚本运行
			for(var i = 0;i<allSequenceArray.length;i++){
				sendTaskState(1,allSequenceArray[i][0].PLATFORM_ID,false);
			}
		}
	};
	
	//监听画布是否被滚动，5秒后画布再次向上跟随当前测试控件
	//判断当前是否滚动控件的容器，
	scrollCanvasBool = true;
	$("#canvasDivAuto").on('mousewheel',function(){
		if(!scrollCanvasBool){
			return;
		}
		scrollCanvasBool = false;
		setTimeout(function(){
			scrollCanvasBool = true;
		}, 5000);
	});
	
});
var idList = [];
// 获取用例元素类型
var elementTypes = [];
var caseElements = [];
var scaleX = 1;
var scaleY = 1;
var currentX = 5; // 上方缩略图X轴起始位置
var canvasTH = document.getElementById("inline"); // canvas绘制上方缩略图
thTDrawCanvas = new TDrawCanvas(canvasTH);
var cth = canvasTH.getContext("2d"); // canvas绘制上方缩略图
canvasTH.height = 54;
var canvas = document.getElementById("canvasId"); // 中间画布区域
var context = canvas.getContext("2d"); // 拿到画布
autoTDrawCanvas = new TDrawCanvas(canvas);
selectSequenceId = 0;// 当前测试的序列id
selectPlatformId = 0;// 当前测试的平台id
platformStartTimeArray = [];// 不同平台对应的序列的开始测试时间
// 分支和循环控件的头填充颜色
titleBackGround = '#222222';
// 分支和循环控件的头文字颜色
initFontColor = '#00AAAA';
// 分支和循环控件的字样式
initLabelStyle = '14px Arial';
// 分支和循环控件宽度
banchLoopWidth = 100;
// 分支和循环控件的高度
banchLoopTitleHeight = 30;
banchLoopHeight = 55;
// 条件控件下方矩形默认高度
banchLoopBottomHeight = 25;
// 初始绘图的坐标
initLocation = {x:15,y:15};
// 控件与控件的间距
betweenTool = 15;
// 小矩形控件的高度
rectHeight = 30;
// 小矩形控件的宽度
rectWidth = 80;
// 容器控件中的条件的第一个位置
conditionPostion = {
	x : 31,
	y : 4
};
// 条件控件之间的间隔
conditionSpace = 23;
// 初始化左侧任务详情信息
function initTestTask(testTaskId) {
	$.ajax({
		url: "../../../testTask/queryTestTaskMessageByTaskId",
		type: "POST",
		data: {
			"taskId": testTaskId
		},
		success: function (data) {
			var content = data.content;
			var taskName = content.taskName;
			var taskCode = content.taskCode;
			var taskDes = content.taskDes;
			var sequenceList = content.sequenceList;
			currentSequenceList = [].concat(JSON.parse(JSON
				.stringify(sequenceList)));
			$('#testTaskName').text(taskName);
			$('#testTaskCode').text(taskCode);
			if(currentTaskCompleteBool && taskStartTime!="undefined"){
				$('#testStartTime').text(taskStartTime);
				$('#testEndTime').text(taskEndTime);
			}else{
				$('#testStartTime').text("-");
				$('#testEndTime').text("-");
				$('#testEndLebal').text("预期结束时间：");
			}
			$('#testTaskInfo').text(taskDes);
			for (var i = 0; i < sequenceList.length; i++) {
				var sequence = sequenceList[i];
				var sequenceName = sequence.SEQUENCE_NAME;
				var sequenceId = sequence.SEQUENCE_ID;
				var sort = sequence.ROWNUM;
				appendSequenceList(sequenceName, sequenceId, sort, i,sequence.PLATFORM_ID,sequence.ID);
				currentSequenceList[i].progress = 0;
				taskIdArray.push(sequence.ID);
			}
			setProgressState();
			selectPlatformId = sequenceList[0].PLATFORM_ID;
			selectSequenceId = sequenceList[0].ID;
			var firstSequenceId = sequenceList[0].SEQUENCE_ID;
			showSequence(firstSequenceId);
			// 把相同的平台分组
			if(currentTaskCompleteBool){
				setSequenceArray(sequenceList);
			}
		}
	});
}

// 根据测试序列id获取当前测试序列的平台id
function getAllPlatformById(sequenceList){
	$.ajax({
		url: '../../../autoTest/applyForPlatform',
		type: 'POST',
		data: {
			taskId: testTaskId// 任务id
		},
		success: function (data) {
			if(data.flag == 0){
				// 把分配好的平台id赋值给序列中老的平台id字段
				for (var i = 0; i < sequenceList.length; i++) {
					for(var j = 0;j<data.content.length;j++){
						if(sequenceList[i].ID == data.content[j].relId){
							sequenceList[i].PLATFORM_ID = data.content[j].platformId;
							break;
						}
					}
				}
				selectPlatformId = sequenceList[0].PLATFORM_ID;
				// 把相同的平台分组
				setSequenceArray(sequenceList);
				currentPPlatformBool = true;
				$('#startCHHF').html("编辑版本号");
				// 当版本信息可以获取成功时，弹出版本信息界面
				checkVersionBool();
			}else{
				currentPPlatformBool = false;
				danger("<div style='color:black'>"+data.errorInfo+"</div>");
			}
		}
	});
}

// 当进度条是0%或者100%时，右侧的开始继续按钮不可点击
function setProgressState(){
	for(var i = 0;i<currentSequenceList.length;i++){
		if(currentSequenceList[i].progress == 100 || currentSequenceList[i].progress == 0){
			$('#btn_'+currentSequenceList[i].ID).attr('disabled',true);
		}else{
			$('#btn_'+currentSequenceList[i].ID).attr('disabled',false);
		}
	}
}
// 把相同的平台分组,为不同的平台同时进行测试做准备
function setSequenceArray(sequenceList){
	var newArr = [].concat(JSON.parse(JSON
	.stringify(sequenceList)));
	var tempId = newArr[0].PLATFORM_ID;
	var j = 0;
	while(newArr.length>0){
		tempId = newArr[0].PLATFORM_ID;
		allSequenceArray[j] = [];
		for(var k = newArr.length - 1;k>=0;k--){
			if(newArr[k].PLATFORM_ID == tempId){
				allSequenceArray[j].push(newArr[k]);
				newArr.splice(k,1);
			}
		}
		j++;
	}
	for(var p=0;p<allSequenceArray.length;p++){
		allSequenceArray[p].reverse();	
		allSequenceComIndex.push(0);
	}
	console.log(allSequenceArray);
	platformStartTimeArray = [].concat(JSON.parse(JSON
			.stringify(allSequenceArray)));
}


// 左侧任务的详细信息显示
function appendSequenceList(sequenceName, sequenceId, sort, index,platformId,id) {
	var li = '';
	if (index == 0) {// 默认第一个是被选中
		li += '<div class = "progressBarSelected allProgress"><div class="progressBar" style="pointer-events: none;" data="' +
			sequenceId+"."+platformId+"."+sort+"."+id + '" onclick="clickSequence(this)" disabled="true" id="pro_'+
			id+'">';
		li += '<label class="form-label ">' + sequenceName + '：</label> ';
		li += '<div class="progress progress-striped active">';
		// li += '<div id="'+ sequenceId+sort
		li += '<div id="' +
		id +
			'" class="progress-bar" role="progressbar" aria-valuenow="" aria-valuemin="0" aria-valuemax="100" style="width:0%;">';
		li += '</div>';
		li += '</div>';
		li += '</div>';
		li += '</div><button  data="' +
		sequenceId+"."+platformId+"."+sort+"."+id + '" onclick="startOrStopTask(this)" class="testBtn" id="btn_' +
		id +
		'" ></button>';
	} else {
		li += '<div class="allProgress"><div class="progressBar" data="' + sequenceId+"."+platformId+"."+sort+"."+id + '" style="pointer-events: none;"  onclick="clickSequence(this)" disabled="true" id="pro_'+
		id+'">';
		li += '<label class="form-label ">' + sequenceName + '：</label> ';
		li += '<div class="progress progress-striped active">';
		// li += '<div id="'+ sequenceId+sort
		li += '<div id="' +
		id +
			'" class="progress-bar" role="progressbar" aria-valuenow="" aria-valuemin="0" aria-valuemax="100" style="width:0%;">';
		li += '</div>';
		li += '</div>';
		li += '</div>';
		li += '</div><button  data="' +
		sequenceId+"."+platformId+"."+sort+"."+id + '" onclick="startOrStopTask(this)" class="testBtn" id="btn_' +
		id +
		'" ></button>';
	}
	$('#sequenceLists').append(li);
}

// 初始化websocket
function initWs(ip) {
	getAllDataWebSocket = new WebSocket('ws://' + ip +
		'/asts/websocket/testServer');
	getAllDataWebSocket.onmessage = function (event) {
		getAllDataWebSocketMessage(event);
	};

	getAllDataWebSocket.onerror = function (event) {
		getAllDataWebSocketError(event);
	};

	getAllDataWebSocket.onopen = function (event) {
		getAllDataWebSocketOpen(event);
	};
}

count0 = 0;
// 从后台获取到所有的需要的数据，包括图片，日志信息，进度，语音数据。
function getAllDataWebSocketMessage(event) {
	testAllLog = eval('(' + event.data + ')');
	console.log(testAllLog);
	if (testAllLog.exception) {// 错误
		// 当任务为测试时，终止测试后，释放平台
		if (!currentTaskCompleteBool) {
			setTaskState(3);
			for (var i = 0; i < allSequenceArray.length; i++) {
				resetPlatformEdit(allSequenceArray[i][0].PLATFORM_ID);
			}
		}
		danger("<div style='color:black'>" + testAllLog.exception + "</div>");
		return;
	}
	// 处理显示图片和语音信息
	pic = testAllLog.imageS;
	voice = testAllLog.voice;
	if (pic != "") {
		// 图片改变
		$("#showDimImg").attr("src",null);
		$("#showDimImg").attr("src",pic);
	}
	console.log("count0");
	console.log(currentElementId);
	console.log(testAllLog.elementId);
	// 语音
	if (voice != "") {
		playVoice(voice.split(":")[0], voice.split(":")[1]);
	}
	// 展示测试序列中的测试用例,根据获取到的索引显示
	if(currentElementId!=testAllLog.elementId){
		managerSequence(Number(testAllLog.caseSort), testAllLog);
	}
	currentElementId = testAllLog.elementId;
	$('.testActiveBtn').removeClass('testActiveBtn');
	$('#startCHHF').attr('disabled', true);
	$('#stopTask').removeAttr('disabled');
	// 左侧进度条显示
	for (var i = 0; i < testAllLog.progress.length; i++) {
		progressUpdate(testAllLog.progress[i].taskRelId,
				testAllLog.progress[i].progression);// 进度条的更新显示
		signTaskStart(testAllLog.progress[i].taskRelId);// 记录当前平台的当前序列的本地开始时间，用来暂停当前序列测试的时间记录
		$("#btn_" + testAllLog.progress[i].taskRelId).addClass('testActiveBtn');
		taskEndTime = testAllLog.time;
		$('#stopTask').removeAttr('disabled');
		if (testAllLog.end) { // 当前测试完成时，断开链接
			$("#btn_" + testAllLog.progress[i].taskRelId).removeClass(
					'testActiveBtn');
			getAllDataWebSocket.close();
			getDmiDataWebSocket.close();
			
			var successpic = "";
			$("#showDimImg").attr("src",null);
			$("#showDimImg").attr("src",successpic);
			
			$('#stopTask').attr('disabled', 'true');
			// 当前是哪个平台索引
			var index = getPlatformIndexByID(testAllLog.progress[i].taskRelId);
			// 当前平台发送第几个测试序列索引
			allSequenceComIndex[index]++;
			if (selectIndex <= allSequenceArray[index].length
					&& allSequenceArray[index][allSequenceComIndex[index]]) {
				selectSequenceId = allSequenceArray[index][allSequenceComIndex[index]].ID;
				if (getProgressById(selectSequenceId) == 0) {// 获取当前id的进度条的进度
					$('#pro_' + selectSequenceId).click();
				}
			} else {
				// 当某个平台测试完成，释放当前平台
				if (!currentTaskCompleteBool) {
					currentTaskState = 2;
					resetPlatformEdit(allSequenceArray[0][allSequenceComIndex[index] - 1].PLATFORM_ID);
					setTaskState(2);
				}
			}
		}
	}
	// 当进度条是0%或者100%时，右侧的开始继续按钮不可点击
	setProgressState();
	// 显示日志
	addAutoLog(testAllLog.time.split('.')[0], testAllLog.log);
}

//获取语音
function playVoice(code, time) {
	if (code) {// 判断返回音效代码是否为空
		var music = $('#bgMusic')[0];
		if (parseInt(code) > 0 && parseInt(time) > 0) {// 开始播放音频
			// console.log("成功：：：：：："+code+"||||"+time);
			// 不重复播放同一个语音
			if (currentVoiceNum != parseInt(code)) {
				// 重置音效播放的次数
				currentPlayTimes = 0;
				// 重置获取到当前音效的信息
				currentVoiceData = {code:code,time:time};
				// 开始播放音效，播放次数为一次的语音之间间隔一秒
				if (time == 1 && currentVoiceNumCopy == parseInt(code)) {
					setTimeout(playVoiceFun, 1000);
				} else {
					playVoiceFun();
				}
				// 记录当前播放音效的code，为了不重复播放用一个音效
				currentVoiceNum = parseInt(code);
				currentVoiceNumCopy = parseInt(code);
			}
		} else {
			// console.log("为0语音"+code+"||||"+time);
			if (!music.paused) {
				music.pause();
				$("#audioBtn").removeClass("play").addClass("pause");
			}
		}
	}
}

// 播放音效
function playVoiceFun(){
	// console.log('开始播放音效');
	var music=$('#bgMusic')[0];
	//音效播放次数加1
	currentPlayTimes++;
	$('#bgMusic').attr('src',"../../textcommon/voice/"+parseInt(currentVoiceData.code)+".mp3");
	music.play();
	$("#audioBtn").removeClass("pause").addClass("play");
}

//监听语音播放完成
function playOver(){
	//console.log("音效播放第"+currentPlayTimes+"次完成");
	//如果播放次数小于当前音效需要的播放的次数，那么再播放一次当前音效
	if(currentPlayTimes<parseInt(currentVoiceData.time)){
		playVoiceFun();
	}else{
		//当前语音播放次数完成后，重置记录的语音code
		if(currentVoiceData.time == 1){
			currentVoiceNum = 0;
		}
	}
}

// 记录当前平台的当前序列的本地开始时间，用来暂停当前序列测试的时间记录
function signTaskStart(id){
	for(var i = 0;i<platformStartTimeArray.length;i++){
		for(var j = 0;j<platformStartTimeArray[i].length;j++){
			if(platformStartTimeArray[i][j].ID == id && !platformStartTimeArray[i][j].localStartTime){
				// 记录当前序列开始测试的本地时间点
				platformStartTimeArray[i][j].localStartTime = Date.parse(new Date());
				break;
			}
		}
	}
}

// 点击暂停后，设置当前测试序列的暂停时间：当前序列的服务器开始时间+（本地时间-开始本地时间）
function setSystemStopTime(id){
	var now = Date.parse(new Date());
	var space = 0;
	for(var i = 0;i<platformStartTimeArray.length;i++){
		for(var j = 0;j<platformStartTimeArray[i].length;j++){
			if(platformStartTimeArray[i][j].ID == id){
				// 序列上次开始测试时间和点击暂停时间的间隔
				space = now - platformStartTimeArray[i][j].localStartTime;
				// 记录当前暂停点对应当前序列的时间
				if(!platformStartTimeArray[i][j].doStopTime){
					platformStartTimeArray[i][j].doStopTime = timestampToTime(timeToTimestamp(platformStartTimeArray[i][j].TEST_START_TIME)+space);
				}else{
					platformStartTimeArray[i][j].doStopTime = timestampToTime(timeToTimestamp(platformStartTimeArray[i][j].doStopTime)+space);
				}
				// 当记录的停止的时间大于改序列的结束时间，那么记录停止时间=改序列的结束时间
				if(timeToTimestamp(platformStartTimeArray[i][j].doStopTime)>
				timeToTimestamp(platformStartTimeArray[i][j].TEST_END_TIME)
				){
					platformStartTimeArray[i][j].doStopTime = platformStartTimeArray[i][j].TEST_END_TIME;
				}
				break;
			}
		}
	}
	return ;
}

// 更新进度条的状态
function progressUpdate(id, value) {
	for(var i = 0;i<currentSequenceList.length;i++){
		if(id == currentSequenceList[i].ID){
			currentSequenceList[i].progress = value;
			break;
		}
	}
	
	$("#" + id).css("width", value + "%").text(value + "%");
	if (value >= 0 && value <100) {
		$("#" + id).addClass("progress-bar-success");
	}  else {
		$("#" + id).parent('.active').removeClass("active");
		return;
	}
}

function getAllDataWebSocketOpen(event) {
	console.log("WS握手成功！");
	// 链接成功后，再发送请求
	if (getAllDataWebSocket.readyState == 1) {
		if(startBtnClickBool){// 在点击开始测试按钮时，同时发送不同平台的第一个测试序列的请求
			for(var i = 0;i<allSequenceArray.length;i++){
				selectSequenceId = allSequenceArray[i][0].ID;
				continueTest();
			}
			startBtnClickBool = false;
		}else{
			continueTest();
		}
	}
}

function getAllDataWebSocketError(event) {
	// 当任务为测试时，终止测试后，释放平台
	if(!currentTaskCompleteBool){
		// 当websocket返回错误时，异常结束
		setTaskState(3);
		for(var i = 0;i<allSequenceArray.length;i++){
			resetPlatformEdit(allSequenceArray[i][0].PLATFORM_ID);
		}
	}
}

function getAllDataWebSocketClose(event) {
	getAllDataWebSocket.close();
}

// websocket传到后台的参数队列
function start() {
	// 当前任务未完成时，首先分配平台id,然后弹出版本信息，设置版本信息，最后开始测试
	if(!currentTaskCompleteBool){
		if(!startTestBool){
			getAllPlatformById(currentSequenceList);
		}else{
			setStartTest();
		}
	}else{// 如果当前任务已经完成，那么为回放
		startBtnClickBool = true;
		setStartTest();
	}
}

// 如果是未完成的状态，则建立websocket前需要调用将测试脚本发到相应平台上执行的方法，如果是完成状态，则可以直接连接websocket发送查询请求
// 先更新任务状态，成功后初始化平台，成功后再创建websocket连接
function setStartTest(){
	if(!currentTaskCompleteBool){// 未通过
		if(!taskStatusBool){// 任务状态只需要更新一次
			$.ajax({
				url: '../../../autoTest/updateTaskInfo',
				type: "POST",
				data: {
					taskId: testTaskId,
					status: 1
				},
				success: function (data) {
					createGetData();
					//改变任务状态成功后，记录下当前状态
					currentTaskState = 1;
				},error:function(){
					for(var i = 0;i<allSequenceArray.length;i++){
						resetPlatformEdit(allSequenceArray[i][0].PLATFORM_ID);
					}
				}
			});
			taskStatusBool = true;
		}else{
			createGetData();
		}
	}else{// 通过
		initWs(path);
		if(!currentTaskCompleteBool){
			initDmiWebSocket(path);
		}
	}
}

// 创建获取数据连接
function createGetData(){
	console.log("开始发送请求测试请求");
	for(var i = 0;i<allSequenceArray.length;i++){
		selectSequenceId = allSequenceArray[i][0].ID;
		$.ajax({
		        url: '../../../autoTest/startAutoTest',
		        type: 'POST',
		        data: {
		          taskRelId:selectSequenceId
		        },
		        success:function(data){
		        	if(data.flag == 0){// 返回成功过后，创建websoket连接
		        		$('#stopTask').removeAttr('disabled');
		        		$("#startBtn").attr("disabled", true);
		        		initWs(path);
		        		if(!currentTaskCompleteBool){
		        			initDmiWebSocket(path);
		        		}
		        		addAutoLog(getNowTime(),data.content);
		        	}else{
		        		//当任务为测试时需要释放平台，回放不用释放
		    			if(!currentTaskCompleteBool){
		    				for(var i = 0;i<allSequenceArray.length;i++){
		    					resetPlatformEdit(allSequenceArray[i][0].PLATFORM_ID);
		    				}
		    			}
		        		danger("<div style='color:black'>"+data.errorInfo+"</div>");
		        		addAutoLog(getNowTime(),data.errorInfo);
		        	}
		        },
		        error: function(){
		        	//当任务为测试时需要释放平台，回放不用释放
					if(!currentTaskCompleteBool){
						for(var i = 0;i<allSequenceArray.length;i++){
							resetPlatformEdit(allSequenceArray[i][0].PLATFORM_ID);
						}
					}
		        }
		 });
	}
}

// 获取当前时间
function getNowTime() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    var strHour = date.getHours();
    var strMinutes = date.getMinutes();
    var strSeconds = date.getSeconds();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if (strHour >= 0 && strHour <= 9) {
    	strHour = "0" + strHour;
    }
    if (strMinutes >= 0 && strMinutes <= 9) {
    	strMinutes = "0" + strMinutes;
    }
    if (strSeconds >= 0 && strSeconds <= 9) {
    	strSeconds = "0" + strSeconds;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
            + " " + strHour + seperator2 + strMinutes
            + seperator2 + strSeconds;
    return currentdate;
}
// 发送请求，获取自动测试数据
function continueTest() {
	var wss = {};
	var ids = $("#sequenceLists div div"); // 拿到所有的序列id
	for (var i = 0; i < ids.length; i++) {
		var id = ids.eq(i).attr("id");
		idList[i] = id;
	}
	var type = 2;// 回放
	if(!currentTaskCompleteBool){
		type = 1;
		getSystemTime(function(res){
			$('#testStartTime').text(res);
			sendTime=res;
			//如果当时任务没有测试过，不是回放，那么给结束时间修改为预期结束时间，一个序列为5分钟
			setExpectTime(res);
			wss.command = "auto";
			wss.content = {
				taskRelId: selectSequenceId,	
				type: type,
				time:sendTime,// 空时代码测试，有时间时为回放
			};
			getAllDataWebSocket.send(JSON.stringify(wss));
		});
	}else{
		type = 2;
		wss.command = "auto";
		wss.content = {
			taskRelId: selectSequenceId,	
			type: type,
			time:sendTime,// 空时代码测试，有时间时为回放
		};
		getAllDataWebSocket.send(JSON.stringify(wss));
	}
	
	$("#startBtn").attr("disabled", true);
	
}

function stop() {
	var sTime = $("label#testStartTime").text();
	var messageInfo = "您确定要终止此次测试么？";
	if(currentTaskCompleteBool){
		messageInfo = "您确定要终止此次回放么？";
	}
	if (sTime == "-") {
		content = "任务还未开始执行！";
		info(content);
	} else {
		BootstrapDialog.show({
			title: '提示',
			message: messageInfo,
			buttons: [{
				label: '确定',
				action: function (dialogRef) {
					dialogRef.close(); 
					if(!currentTaskCompleteBool){
						getSystemTime(function(res){
							$('#testEndTime').text(res);
						});
					}
					$("#startBtn").attr("disabled", false);
					$('#stopTask').attr('disabled',true);
					getAllDataWebSocket.close();
					//发送停止脚本运行
					for(var i = 0;i<allSequenceArray.length;i++){
						sendTaskState(1,allSequenceArray[i][0].PLATFORM_ID,true);
					}
					// 当任务为测试时，终止测试后，释放平台
					if(!currentTaskCompleteBool){
						for(var i = 0;i<allSequenceArray.length;i++){
							resetPlatformEdit(allSequenceArray[i][0].PLATFORM_ID);
						}
						//更新任务状态
						setTaskState(2);
					}
				}
			}, {
				label: '取消',
				action: function (dialogRef) {
					dialogRef.close();
				}
			}]
		});
	}
}

// 初始化进度条
function initProcess() {
	// 进度条复位函数
	function reset() {
		value = 0;
		$("#prog").removeClass("progress-bar-success").css("width", "0%").text(
			"等待启动");
	}
}

// 查看dmi看板
function lookDmi() {
	if(getDmiDataWebSocket.readyState!=1){
		initDmiWebSocket(path);
	}
	BootstrapDialog
	.show({
		title: 'DMI信息看板',
		cssClass: "dmi-dialog",
		message: "<div id='showDim' ></div>",
		onhide:function(){
			getDmiDataWebSocket.close();
		}

	});
}

// dmi websocket 初始化
function initDmiWebSocket(ip) {
	getDmiDataWebSocket = new WebSocket('ws://' + ip + '/asts/websocket/testServer');
	getDmiDataWebSocket.onmessage = function (event) {
		getDmiDataWebSocketMessage(event);
	};
	getDmiDataWebSocket.onerror = function (event) {
		getDmiDataWebSocketError(event);
	};
	getDmiDataWebSocket.onopen = function (event) {
		getDmiDataWebSocketOpen(event);
	};
	getDmiDataWebSocket.onclose = function (event) {
		getDmiDataWebSocketClose(event);
	};
}

count1 = 0;
function getDmiDataWebSocketMessage(event) {
	 dmiVoice = eval('(' + event.data + ')');
	 pic = dmiVoice.imageS;
	 voice = dmiVoice.voice;
	//处理显示图片和语音信息
	if(pic!=""){
		var myDate = new Date();
		myDate.toLocaleDateString();     //获取当前日期
		var mytime=myDate.toLocaleTimeString();     //获取当前时间
		console.log(mytime);
		// 图片改变
		$("#showDimImg").attr("src",null);
		$("#showDimImg").attr("src",pic);
		count1++;
		console.log("第二个");
		console.log(count1);
	}
	//语音
	if(voice!=""){
		playVoice(voice.split(":")[0],voice.split(":")[1]);
	}
}



function getDmiDataWebSocketError(event) {
	console.log(event.data);
}

function getDmiDataWebSocketOpen(event) {
	console.log("DMI WebSocket连接开始！");
	var type = 2;// 回放
	if(!currentTaskCompleteBool){
		type = 1;
		taskStartTime = "";
		taskEndTime = "";
	}
		var param = {
				"command": "autoDmi",
				"content": {
					"taskRelId": selectSequenceId,
					"type": type,
					"time": taskStartTime
				}
			};
		getDmiDataWebSocket.send(JSON.stringify(param));
}

function getDmiDataWebSocketClose(event) {
	console.log("WebSocket连接关闭！");
}

// 点击测试任务内的测试序列，获取点击的测试序列的ID
function clickSequence(p) {
	// 当前无可用平台
	if(!currentPPlatformBool){
		warning(currentPStr);
		return;
	}
	$('.progressBarSelected').removeClass('progressBarSelected');
	$(p).addClass('progressBarSelected');
	selectSequenceId = p.getAttribute("data").split('.')[3];// 当前点击的序列的id
	allCompleteBool = false; // 点击测试序列时重置为false;
	if(testTaskState!=3){//当前如果是暂停后，继续测试，那么不需要重新获取序列信息，为了防止序列信息中已测试过的控件状态被重置
		showSequence(p.getAttribute("data").split('.')[0]);
	}
	if (getAllDataWebSocket && (getAllDataWebSocket.readyState == 1)) { // 点击按钮时，先把上个连接断开
		getAllDataWebSocket.close();
	}
	selectIndex = p.getAttribute("data").split('.')[2];
	// 当前是哪个平台索引
	var index = getPlatformIndexByID(selectSequenceId);
// //当前点击第几个测试序列索引
	allSequenceComIndex[index] = p.getAttribute("data").split('.')[2] - 1;
	
	// 把当前继续的时间点记录为开始测试的时间点
	var now = Date.parse(new Date());
	
	if(getProgressById(selectSequenceId) == 0){
		sendTime = getStatrTimeById(selectSequenceId);
	}else{
		// 开始创建连接
		for(var i = 0;i<platformStartTimeArray.length;i++){
			for(var j = 0;j<platformStartTimeArray[i].length;j++){
				if(platformStartTimeArray[i][j].ID == selectSequenceId){
					platformStartTimeArray[i][j].localStartTime = now;
					sendTime = platformStartTimeArray[i][j].doStopTime;
					break;
				}
			}
		}
	}
	if(currentTaskCompleteBool){// 当前任务为已完成状态，回放
		initWs(path);	
	}else{
		$('#stopTask').removeAttr('disabled');
		$("#startBtn").attr("disabled", true);
		initWs(path);
		initDmiWebSocket(path);
	}
	
	return false;
}

// 展示测试序列中的测试用例
function showSequence(sequenceId) {
	$.ajax({
		url: '../../../sequence/querySequenceContentById',
		type: 'POST',
		data: {
			sequenceId: sequenceId
		},
		success: function (data) {
           if(data.flag==0){
        	   showSequenceIndex(data, 0);
			}else{
				danger("<div style='color:black'>"+data.errorInfo+"</div>");
			}
		}
	});
}
// 展示测试序列中的测试用例,根据获取到的索引显示
function showSequenceIndex(data, index,getObj) {
	var dataJsonStr = data.content.sequenceContent;
	querySequenceArray = eval(dataJsonStr); // 拿到测试序列内的基本用例
	managerSequence(index,getObj);
}

currentElementId = 0;
//显示测试序列菜单和绘制测试序列
function managerSequence(index,getObj){
	console.log("123123123");
	if(querySequenceArray == null){
		return;
	}
	currentX = 5;
	
	//实现任务中测试序列的基本用例个数，实现均匀排版
	var totalWidth0 = 0;
	for (var i = 0; i < querySequenceArray.length; i++) {
		if(querySequenceArray[i].name.length<=6){
			querySequenceArray[i].width = 145+30;
		}else{
			querySequenceArray[i].width = querySequenceArray[i].name.length*21;
		}
		totalWidth0 = totalWidth0+querySequenceArray[i].width+10;
	}
	if((totalWidth0+100)<=755){
		canvasTH.width=775;
	}else{
		canvasTH.width = totalWidth0+100;
	}
	if (querySequenceArray.length != 0) {
		for (var i = 0; i < querySequenceArray.length; i++) {
			// 给当前的基本用例设置属性，用于绘制缩略图
			if(querySequenceArray[i].name.length<=6){
				querySequenceArray[i].width = 145+30;
			}else{
				querySequenceArray[i].width = getStrLength(querySequenceArray[i].name)*12+30;
			}
			
			querySequenceArray[i].height = 35;
			querySequenceArray[i].x = currentX;
			querySequenceArray[i].y = 3;
			querySequenceArray[i].x1 = querySequenceArray[i].x;
			querySequenceArray[i].x2 = querySequenceArray[i].x + querySequenceArray[i].width;
			querySequenceArray[i].y1 = querySequenceArray[i].y;
			querySequenceArray[i].y2 = querySequenceArray[i].y + querySequenceArray[i].height;
			var thTdrawCanvas;
			if (i == index) {
				querySequenceArray[i].color = "rgb(255,0,0)";
				thTdrawCanvas = thTDrawCanvas.getDrawing('thumbnails', {
					baseCase: querySequenceArray[i],
					color: querySequenceArray[i].color,
					filled: true,
					filledColor: "rgb(85, 107, 47)"
				});
			} else {
				querySequenceArray[i].color = "rgb(128,138,135)";
				thTdrawCanvas = thTDrawCanvas.getDrawing('thumbnails', {
					baseCase: querySequenceArray[i],
					color: querySequenceArray[i].color
				});
			}
			thTdrawCanvas.draw();
			
			//绘制测试序列
			caseElements = eval(querySequenceArray[index].caseContent); // 默认展示序列的第一个基本用例
			var lastWidth = caseElements[caseElements.length - 1].x+caseElements[caseElements.length - 1].width+200;
			if(lastWidth<1000){
				canvas.width = 1000;
			}else{
				canvas.width = lastWidth;
			}
			//进入界面后，清除控件的选中属性，websocket的时候不需要重置状态
			if(getObj == null){
				resetSelected();
			}
			context.clearRect(0, 0, canvas.width, canvas.height);
			for (var j = 0; j < caseElements.length; j++) {
				setDrawSize(caseElements[j]);
			}
			resetCanvasHeight();
			// 完成的条件轴状态设置
			if (getObj && getObj.elementId != "") {
				//根据websocket接受的数据，判断哪个控件正在执行
				setSelectedById(getObj.elementId,caseElements,getObj);
				reSetAllChildrenSatus(getObj.elementId,caseElements);
			}
			drawProcessChart(caseElements);
			//把当前基本用例的数据赋值给基本用例字符串，为了实现执行过的状态不会被重置
			querySequenceArray[index].caseContent = JSON.stringify(caseElements);
			
			currentX += querySequenceArray[i].width+10;
		}
	}
}

//当循环控件执行第二遍及第二遍以上时，重置当前循环内的绘图状态重新绘图
function reSetAllChildrenSatus(id,caseElements){
	for(var i = 0;i<caseElements.length;i++){
		if(id == caseElements[i].id && caseElements[i].type == "016"){
			for (var j = 0; j < caseElements[i].childrens.length; j++) {
				loopReSetSelected(caseElements[i].childrens[j]);
			}
			for (var j = 0; j < caseElements[i].leftChildrens.length; j++) {
				loopReSetSelected(caseElements[i].leftChildrens[i]);
			}
			for (var j = 0; j < caseElements[i].rightChildrens.length; j++) {
				loopReSetSelected(caseElements[i].rightChildrens[j]);
			}
			break;
		}
		
		reSetAllChildrenSatus(id,caseElements[i].childrens);
		reSetAllChildrenSatus(id,caseElements[i].leftChildrens);
		reSetAllChildrenSatus(id,caseElements[i].rightChildrens);
	}
}

//根据websocket接受的数据，判断哪个控件正在执行
//当result为“FALSE”时，控件显示为红色，result为其他值时，标志当前控件已经完成，显示绿色
function setSelectedById(id,caseElements,getObj){
	for(var i = 0;i<caseElements.length;i++){
		if(id == caseElements[i].id){
			if(getObj.result == "FALSE"){
				caseElements[i].stateType = 3;
			}else{
				caseElements[i].selected = true;
			}
			
			//画布向上滚动到当前控件位置,当没有鼠标滚动时才可以自动滚动
			if(scrollCanvasBool){
				testingScrollY = caseElements[i].y +300 - 495;
				if((caseElements[i].y+300) <= 495){
					testingScrollY = 0;
				}
				$("#canvasDivAuto").scrollTop(testingScrollY);
			}
		}
		setSelectedById(id,caseElements[i].childrens,getObj);
		setSelectedById(id,caseElements[i].leftChildrens,getObj);
		setSelectedById(id,caseElements[i].rightChildrens,getObj);
	}
}

// 条件轴状态刷新以后，横滚动条滚动位置
function updateScrollPostion(caseElementsCell) {
	$('#canvasDivAuto').scrollLeft(caseElementsCell.x - 50);
}

/* 绘制右上方的模式曲线示意图 */
function drawGraph(canvas) {
	var ctx = canvas.getContext('2d');
	ctx.beginPath(); /* 右上方的矩形示意图 */
	ctx.strokeRect(625, 5, 175, 80);
	var text = "曲线示意图";
	ctx.fillText(text, 625, 10);
	ctx.stroke();
	var img = new Image(); /* 绘制图片 */
	img.src = "../../images/curve.PNG";
	img.onload = function () {
		ctx.drawImage(img, 625, 25);
	};
}

// 画出机车线路数据
function updateData(data) {
	var canvase = $("#lineCanvas");
	drawLine(data, canvase);
}


// 开始和暂停序列测试
// type 1表示停止脚本运行。2表示暂停脚本运行。3表示恢复继续运行。
function startOrStopTask(p){
	var id = p.getAttribute("data").split('.')[3];
	var platformId = p.getAttribute("data").split('.')[1];
	selectSequenceId = id;
	if($(p).hasClass('testActiveBtn')){
		$(p).removeClass('testActiveBtn');
		testTaskState = 2;// 暂停序列
		setSystemStopTime(id);
		getAllDataWebSocket.close();
		addAutoLog(getNowTime(),"暂停测试！");

	}else{
		$(p).addClass('testActiveBtn');
		testTaskState = 3;// 继续序列
		$('#pro_' + id).click();
		addAutoLog(getNowTime(),"继续测试！");

	}
	// 当时测试时，需要发送cs的请求脚本
	if(!currentTaskCompleteBool){
		sendTaskState(testTaskState,platformId,true);
	}
}

// 点击继续测试按钮
function taskContainueTest(id){
	// 把当前继续的时间点记录为开始测试的时间点
	var now = Date.parse(new Date());
	
	if(getProgressById(id) == 0){
		$('#pro_' + id).click();
	}else{
		// 开始创建连接
		for(var i = 0;i<platformStartTimeArray.length;i++){
			for(var j = 0;j<platformStartTimeArray[i].length;j++){
				if(platformStartTimeArray[i][j].ID == id){
					platformStartTimeArray[i][j].localStartTime = now;
					sendTime = platformStartTimeArray[i][j].doStopTime;
					break;
				}
			}
		}
	}
	 setStartTest();
}

// 获取当前id的进度条的进度
function getProgressById(id){
	var value = 0;
	for(var i = 0;i<currentSequenceList.length;i++){
		if(currentSequenceList[i].ID == id){
			value = currentSequenceList[i].progress;
			break;
		}
	}
	return value;
}

// 获取当前id的开始测试时间
function getStatrTimeById(id){
	var time = "";
	for(var i = 0;i<currentSequenceList.length;i++){
		if(currentSequenceList[i].ID == id){
			time = currentSequenceList[i].TEST_START_TIME;
			break;
		}
	}
	return time;
}

// 发送控制自动测试的暂停、续测、终止操作指令
function sendTaskState(type,platformId,tipBool){
	if(currentTaskCompleteBool){// 回放中不需要调用cs接口，开始测试中需要调用cs接口
		return;
	}
	$.ajax({
        url: '../../../autoTest/autoTest',
        type: 'POST',
        data: {
        	type:type,
        	platformId:platformId
        },
        success:function(data){
        	if(!tipBool){
        		return;
        	}
        	var flag = data.flag;
			if (flag != 0) {
				danger("<div style='color:black'>"+data.errorInfo+"</div>");
			}
        },
        error: function(){
         alert("error");
        }
 });
}

// 开始测试或者回放前展示版本信息
function showVersion(){
	BootstrapDialog.show({
		title: '版本信息',
		message: $("<form class='form-inline' style='height:540px;margin-top:-20px;' id='versionHtml'></form>").load('../../textcommon/html/versionView.html'),
		onshown: function() {
			startTestBool = true;
			showVersionViewData();
		},
		buttons: [{
			icon: 'glyphicon glyphicon-check',
			label: '开始测试',
			cssClass: 'btn-primary',
			autospin: true,
			action: function(dialogRef) {
				// 开始测试
				setStartTest();
				dialogRef.close();
			}
		}, {
			label: '取消',
			action: function(dialogRef) {
				dialogRef.close();
			}
		}]
	});
}

// 查看版本信息展示版本信息
function checkVersion(){
	BootstrapDialog.show({
		title: '版本信息',
		message: $("<form class='form-inline' style='height:540px;margin-top:-20px;' id='versionHtml'></form>").load('../../textcommon/html/versionView.html'),
		onshown: function() {
			checkVersionViewData();
		},
		buttons: [{
			icon: 'glyphicon glyphicon-check',
			label: '确定',
			cssClass: 'btn-primary',
			autospin: true,
			action: function(dialogRef) {
				dialogRef.close();
			}
		}]
	});
}

// 版本的信息显示
function checkVersionViewData(){
	$('#myTab li:eq(0) a').tab('show');
	selectVersionIndex = 0;
	if(allSequenceArray.length<=1){
		$('#versionTabDiv').css('display','none');
		$('#versionHtml').css("height",'500px');
	}else{
		$('.versionDiv').css("height",'465px');
		var htmlData = '';
		var htmlData1 = "";
		for(var i = 0;i<allSequenceArray.length;i++){
			if(i == 0){
				htmlData= htmlData +'<li class="active"><a href="#home'+
				i+'" data-toggle="tab">平台'+(i+1)+'</a></li>';
				
				htmlData1 = htmlData1 +'<div class="tab-pane fade in active" id="home'+
				i+'"><div  class="toolbarEdit'+i+'" class="btn-group"><button class="btn_edit" type="button" class="btn btn-default" onclick="editVersion()"><span class="glyphicon glyphicon-pencil"></span>修改</button></div><div class="versionDiv"><table id="versionTableDetail'
				+i+'"></table></div></div>';
			}else{
				htmlData= htmlData +'<li><a href="#home'+
				i+'" data-toggle="tab">平台'+(i+1)+'</a></li>';
				
				htmlData1 = htmlData1 +'<div class="tab-pane fade" id="home'+
				i+'"><div  class="toolbarEdit'+i+'" class="btn-group"><button class="btn_edit" type="button" class="btn btn-default"onclick="editVersion()"><span class="glyphicon glyphicon-pencil"></span>修改</button></div><div class="versionDiv"><table id="versionTableDetail'
				+i+'"></table></div></div>';
			}
		}
		$('#myTab').html(htmlData);
		$('#myTabContent').html(htmlData1);
	}
	if(currentTaskCompleteBool){
		$('.btn_edit').css('display','none');
	}
	
	for(var i = 0;i<allSequenceArray.length;i++){
		$('#versionTableDetail'+i).bootstrapTable({
			url : '../../../SoftwareVersionChange/getTestVersionByRelId', // 请求后台的URL（*）
			method : "POST",
			contentType : "application/x-www-form-urlencoded",
			toolbar : ".toolbarEdit"+i,
			striped : true, // 是否显示行间隔色
			cache : false, // 是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
			pagination : false, // 是否显示分页（*）
			sortable : true, // 是否启用排序
			checkboxHeader : false,// 是否显示表头的全选
			queryParamsType : "undefined", // 默认limit
			queryParams : {relid:currentSequenceList[i].ID},// 传递参数（*）
			sidePagination : "server", // 分页方式：client客户端分页，server服务端分页（*）
			pageNumber : 1, // 初始化加载第一页，默认第一页
			pageSize : 10, // 每页的记录行数（*）
			pageList : [ 10, 25, 50, 100 ], // 可供选择的每页的行数（*）
			search : false, // 是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
			strictSearch : true,
			showColumns : true, // 是否显示所有的列
			minimumCountColumns : 2, // 最少允许的列数
			clickToSelect : true, // 是否启用点击选中行
			height : 500,// 行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
			uniqueId : "type", // 每一行的唯一标识，一般为主键列
			showToggle : true, // 是否显示详细视图和列表视图的切换按钮
			cardView : false, // 是否显示详细视图
			detailView : false,
			singleSelect:false,
			responseHandler : function(res) {
				return {
					"total": res.content.length, // 总页数
					"rows" : res.content
				// 数据
				};
			}, // 是否显示父子表
			columns : [  {
				field : 'TYPE',
				title : '名称',
				formatter:nameFormatterShow
			}, {
				field : 'TYPE_XIBIE',
				title : '系别',
				formatter:xiFormatterShow
			}, {
				field : 'TYPE_AB',
				title : '类别',
				formatter:ABFormatterShow
			}, {
				field : 'VERSION',
				title : '版本号',
				formatter:VersionFormatterShow
			}, {
				field : 'COMPILEDATE',
				title : '时间',
				formatter:dateFormatterShow
			} ]
		});
	}
	
}



// 查看版本的变量处理函数
// 版本号格式
function VersionFormatterShow(value, row, index) {
	var version = "";
	if(row.VERSION != ""){
		version = row.VERSION;
	}else{
		version = "-";
	}
	return version;
}
// 名称格式
function nameFormatterShow(value, row, index) {
	return getVersionNameByType(row.TYPE);
}
// 日期格式
function dateFormatterShow(value, row, index) {
	var time = "";
	if(row.COMPILEDATE != ""){
		time = row.COMPILEDATE;
	}else{
		time = "-";
	}
	return time;
}
// 系别格式
function xiFormatterShow(value, row, index) {
	var str1 = "1,3,4,5,6";
	var str2 = "7,8,9,10,11,12,13";
	var type = row.TYPE;
	var xibie = "";
	if(str1.indexOf(type)>=0){
		if(row.TYPE_XIBIE == 1){
			xibie = "I 端";
		}else{
			xibie = "II端";
		}
	}else if(type==2){
		if(row.TYPE_XIBIE == 1){
			xibie = "I 端";
		}else{
			xibie = "II端";
		}
	}else if(str2.indexOf(type)>=0){
		if(row.TYPE_XIBIE == 1){
			xibie = "I 系";
		}else{
			xibie = "II系";
		}
	}else if((type==14)){
		if(row.TYPE_XIBIE == 1){
			xibie = "I 系";
		}else{
			xibie = "II系";
		}
	}else if(type==16){
		if(row.TYPE_XIBIE == 1){
			xibie = "I 系";
		}else{
			xibie = "II系";
		}
	}else if((type==15||type==17||type==19||type==21)){
		xibie = "-";
	}else{
		xibie = "-";
	}
	return xibie;
}
// AB格式
function ABFormatterShow(value, row, index) {
	var AB = "";
	var str1 = "1,3,4,5,6";
	var str2 = "7,8,9,10,11,12,13";
	var type = row.TYPE;
	if(str1.indexOf(type)>=0){
		if(row.TYPE_AB == 1){
			AB = "A机";
		}else{
			AB = "B机";
		}
	}else if(type==2){
		AB = "-";
	}else if(str2.indexOf(type)>=0){
		if(row.TYPE_AB == 1){
			AB = "A模";
		}else{
			AB = "B模";
		}
	}else if((type==14)){
		AB = "-";
	}else if(type==16){
		AB = "-";
	}else if((type==15||type==17||type==19||type==21)){
		AB = "-";
	}else{
		AB = "-";
	}
	return AB;
}

// 版本的信息显示编辑
function showVersionViewData(){
	$('#myTab li:eq(0) a').tab('show');
	selectVersionIndex = 0;
	if(allSequenceArray.length<=1){
		$('#versionTabDiv').css('display','none');
		$('#versionHtml').css("height",'500px');
	}else{
		$('.versionDiv').css("height",'465px');
		var htmlData = '';
		var htmlData1 = "";
		for(var i = 0;i<allSequenceArray.length;i++){
			if(i == 0){
				htmlData= htmlData +'<li class="active"><a href="#home'+
				i+'" data-toggle="tab">平台'+(i+1)+'</a></li>';
				
				htmlData1 = htmlData1 +'<div class="tab-pane fade in active" id="home'+
				i+'"><div  class="toolbarEdit'+i+'" class="btn-group"><button class="btn_edit" type="button" class="btn btn-default" onclick="editVersion()"><span class="glyphicon glyphicon-pencil"></span>修改</button></div><div class="versionDiv"><table id="versionTableDetail'
				+i+'"></table></div></div>';
			}else{
				htmlData= htmlData +'<li><a href="#home'+
				i+'" data-toggle="tab">平台'+(i+1)+'</a></li>';
				
				htmlData1 = htmlData1 +'<div class="tab-pane fade" id="home'+
				i+'"><div  class="toolbarEdit'+i+'" class="btn-group"><button class="btn_edit" type="button" class="btn btn-default"onclick="editVersion()"><span class="glyphicon glyphicon-pencil"></span>修改</button></div><div class="versionDiv"><table id="versionTableDetail'
				+i+'"></table></div></div>';
			}
		}
		$('#myTab').html(htmlData);
		$('#myTabContent').html(htmlData1);
	}
	if(currentTaskCompleteBool){
		$('.btn_edit').css('display','none');
	}
	for(var i = 0;i<allSequenceArray.length;i++){
		$('#versionTableDetail'+i).bootstrapTable({
			url : '../../../SoftwareVersionChange/getSoftwareVersion', // 请求后台的URL（*）
			method : "POST",
			contentType : "application/x-www-form-urlencoded",
			toolbar : ".toolbarEdit"+i,
			striped : true, // 是否显示行间隔色
			cache : false, // 是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
			pagination : false, // 是否显示分页（*）
			sortable : true, // 是否启用排序
			checkboxHeader : false,// 是否显示表头的全选
			queryParamsType : "undefined", // 默认limit
			queryParams : {id:allSequenceArray[i][0].PLATFORM_ID},// 传递参数（*）
			sidePagination : "server", // 分页方式：client客户端分页，server服务端分页（*）
			pageNumber : 1, // 初始化加载第一页，默认第一页
			pageSize : 10, // 每页的记录行数（*）
			pageList : [ 10, 25, 50, 100 ], // 可供选择的每页的行数（*）
			search : false, // 是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
			strictSearch : true,
			showColumns : true, // 是否显示所有的列
			minimumCountColumns : 2, // 最少允许的列数
			clickToSelect : true, // 是否启用点击选中行
			height : 500,// 行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
			uniqueId : "type", // 每一行的唯一标识，一般为主键列
			showToggle : true, // 是否显示详细视图和列表视图的切换按钮
			cardView : false, // 是否显示详细视图
			detailView : false,
			singleSelect:false,
			responseHandler : function(res) {
				return {
					"total": res.content.length, // 总页数
					"rows" : res.content
				// 数据
				};
			}, // 是否显示父子表
			columns : [ {
				checkbox : true,
			}, {
				field : 'type',
				title : '名称',
				formatter:nameFormatter
			}, {
				field : 'typeXiBie',
				title : '系别',
				formatter:xiFormatter
			}, {
				field : 'typeAB',
				title : '类别',
				formatter:ABFormatter
			}, {
				field : 'version',
				title : '版本号',
				formatter:VersionFormatter
			}, {
				field : 'date',
				title : '时间',
				formatter:dateFormatter
			} ]
		});
	}
	
}
// 版本号格式
function VersionFormatter(value, row, index) {
	var version = "";
	if(row.version != ""){
		version = row.version;
	}else{
		version = "-";
	}
	return version;
}
// 名称格式
function nameFormatter(value, row, index) {
	return getVersionNameByType(row.type);
}
// 日期格式
function dateFormatter(value, row, index) {
	var time = "";
	if(row.date != ""){
		time = row.date;
	}else{
		time = "-";
	}
	return time;
}
// 系别格式
function xiFormatter(value, row, index) {
	var str1 = "1,3,4,5,6";
	var str2 = "7,8,9,10,11,12,13";
	var type = row.type;
	var xibie = "";
	if(str1.indexOf(type)>=0){
		if(row.typeXiBie == 1){
			xibie = "I 端";
		}else{
			xibie = "II端";
		}
	}else if(type==2){
		if(row.typeXiBie == 1){
			xibie = "I 端";
		}else{
			xibie = "II端";
		}
	}else if(str2.indexOf(type)>=0){
		if(row.typeXiBie == 1){
			xibie = "I 系";
		}else{
			xibie = "II系";
		}
	}else if((type==14)){
		if(row.typeXiBie == 1){
			xibie = "I 系";
		}else{
			xibie = "II系";
		}
	}else if(type==16){
		if(row.typeXiBie == 1){
			xibie = "I 系";
		}else{
			xibie = "II系";
		}
	}else if((type==15||type==17||type==19||type==21)){
		xibie = "-";
	}else{
		xibie = "-";
	}
	return xibie;
}
// AB格式
function ABFormatter(value, row, index) {
	var AB = "";
	var str1 = "1,3,4,5,6";
	var str2 = "7,8,9,10,11,12,13";
	var type = row.type;
	if(str1.indexOf(type)>=0){
		if(row.typeAB == 1){
			AB = "A机";
		}else{
			AB = "B机";
		}
	}else if(type==2){
		AB = "-";
	}else if(str2.indexOf(type)>=0){
		if(row.typeAB == 1){
			AB = "A模";
		}else{
			AB = "B模";
		}
	}else if((type==14)){
		AB = "-";
	}else if(type==16){
		AB = "-";
	}else if((type==15||type==17||type==19||type==21)){
		AB = "-";
	}else{
		AB = "-";
	}
	return AB;
}

// 根据父节点ID获取当前软件版本下都有哪些类型的软件
function getVersionTypesName(sId){
	var content=null;
	$.ajax({
		url : "../../../LKJSoftwareVersion/getTypeName",
		type : "post",
		data : {
			"sId" : sId,
			"type" : ""
		},
		dataType : "json",
		async:false,
		success : function(data) {
			if(data.flag==0){
				content = data.content;
			}else{
				danger("<div style='color:black'>"+data.errorInfo+"</div>");
			}
		},
		error : function() {
		}
	});
	return content;
}

// 根据类型获取当前版本的名称
function getVersionNameByType(type){
	var name = "";
	for(var i = 0;i<versionTypesName.length;i++){
		if(versionTypesName[i].TYPE == type){
			name = versionTypesName[i].SYS_NAME;
			break;
		}
	}
	return name;
}

// 编辑版本
function editVersion(){
	selectCases = $("#versionTableDetail"+selectVersionIndex).bootstrapTable('getSelections');
	
	if(selectCases.length<=0){
		danger("请选择修改的版本！");
		return;
	}
// $.each(BootstrapDialog.dialogs,function(id,dialogs){
// dialogs.close();
// });
	BootstrapDialog.show({
		title: '编辑版本信息',
		message: $("<form class='form-inline' style='height:500px'></form>").load('../../textcommon/html/versionEditView.html'),
		onshown: function() {
			showEditViewData();
		},
		buttons: [{
			icon: 'glyphicon glyphicon-check',
			label: '完成',
			cssClass: 'btn-primary',
			autospin: true,
			action: function(dialogRef) {
				dialogRef.close();
				// 修改成功后，刷新版本界面
				$('#versionTableDetail'+selectVersionIndex).bootstrapTable('refresh');
			}
		}]
	});
}

// 显示要修改的版本信息内容
function showEditViewData(){
	ip = location.host;
	versionChangeWebSocket = null;
	softIds = [];
	getVersionTypes();
}

// 初始化右侧版本换装内容
function getVersionTypes(){
	$("#content").empty();
	softIds = [];
// var content=[{ID:"1",SYS_NAME:"LKJ软件版本"},{ID:"4",SYS_NAME:"ASTS软件版本"}];
	var content=[{ID:"1",SYS_NAME:"LKJ软件版本"}];
		for(var i=0;i<content.length;i++){
			str ="";
			str+='<div class="module" id='+content[i].ID+'><h4>';
			str+=content[i].SYS_NAME;
			str+='</h4>';
			str+=getSelectValue(getVersionTypesNameCheck(content[i].ID));
			$("#content").append(str);
		}
		 $('.multipleSelect').multiselect( { enableClickableOptGroups: true,
	         enableCollapsibleOptGroups: true,
	         includeSelectAllOption: true}
			            );
}
// 根据父节点ID获取当前软件版本下都有哪些类型的软件
function getVersionTypesNameCheck(sId){
	var content=null;
	$.ajax({
		url : "../../../LKJSoftwareVersion/getTypeName",
		type : "post",
		data : {
			"sId" : sId,
			"type" : ""
		},
		dataType : "json",
		async:false,
		success : function(data) {
			if(data.flag==0){
				content = data.content;
			}else{
				content="";
			}
		},
		error : function() {
		}
	});
	for(var i = content.length-1;i>=0;i--){
		var bool = false;
		for(var j = 0;j<selectCases.length;j++){
			if(content[i].TYPE ==selectCases[j].type){
				bool = true;
			}
		}
		if(!bool){
			content.splice(i,1);
		}
	}
	return content;
}
// 将查询到的软件类型进行组装展示各个标签
function getSelectValue(content){
	var str="";
	if(content!=""&&content!=null){
		for(var i=0;i<content.length;i++){
			var id = content[i].SID;// 软件大类：1，lkj软件，4.asts软件
			var type = content[i].TYPE;// 软件类型
			var softId = id+"_"+type;
			softIds.push(softId);
			str+='<div id='+softId+' class="versionDivCell"><span class="spans">';
			str+=content[i].SYS_NAME;
			str+='</span><select class="signSelect">';
			str+=getVersionName(id,type);
		}
	}
	return str;
}
// 根据序列id获取当前返回的数据是相同平台合并后的数组的第几个元素，
function getPlatformIndexByID(id){
	var index = 0;
	for(var i = 0;i<allSequenceArray.length;i++){
		for(var j = 0;j<allSequenceArray[i].length;j++){
			if(allSequenceArray[i][j].ID == id){
				index = i;
				break;
			}
		}
	}
	return index;
}
// 根据版本类型和软件类型查询下拉文件内容
function getVersionName(id,type){
	var str="";
	$.ajax({
		url : "../../../LKJSoftwareVersion/getVersionName",
		type : "post",
		data : {
			"sId" : id,
			"type" : type
		},
		dataType : "json",
		async:false,
		success : function(data) {
			if(data.flag==0){
				var content = data.content;
				str=ajaxOption(content);
			}
		},
		error : function() {
		}
	});
	str+='</select>';
	var str1 = "1,3,4,5,6";
	var str2 = "7,8,9,10,11,12,13";
	if(id==1&&str1.indexOf(type)>=0){
		str+="<select class='multipleSelect' multiple='multiple' > <optgroup label='I 端' class='group-1'><option value='1-1'>A机</option>"+
        "<option value='1-2' >B机</option> </optgroup><optgroup label='II端' class='group-2'>"+
        "<option value='2-1'>A机</option><option value='2-2'>B机</option> </optgroup></select>";
	}else if(id==1&&type==2){
		str+="<select class='multipleSelect' multiple='multiple'><option value='1'>I 端</option><option value='2'>II端</option></select>";
	}else if(id==1&&str2.indexOf(type)>=0){
		str+="<select class='multipleSelect' multiple='multiple' > <optgroup label='I 系' class='group-1'><option value='1-1'>A模</option>"+
        "<option value='1-2' >B模</option> </optgroup><optgroup label='II系' class='group-2'>"+
        "<option value='2-1'>A模</option><option value='2-2'>B模</option> </optgroup></select>";
	}else if(id==1&&(type==14)){
		str+="<select class='multipleSelect' multiple='multiple'><option value='1'>I 系</option><option value='2'>II系</option></select>";
	}else if(id==1&&type==16){
		str+="<select class='multipleSelect' multiple='multiple' >" +
				" <optgroup label='电源' class='group-1'><option value='1-1'>I 系</option><option value='1-2' >II系</option> </optgroup>" +
        "<optgroup label='数字' class='group-2'><option value='2-1'>I 系</option><option value='2-2'>II系</option></optgroup>" +
        "<optgroup label='模拟' class='group-3'><option value='3-1'>I 系</option><option value='3-2'>II系</option> </optgroup>" +
        "<optgroup label='通信' class='group-4'><option value='4-1'>I 系</option><option value='4-2'>II系</option> </optgroup>" +
        "<optgroup label='主控' class='group-5'><option value='5-1'>I 系</option><option value='5-2'>II系</option> </optgroup>" +
        "<optgroup label='检测' class='group-6'><option value='6-1'>I 系</option><option value='6-2'>II系</option> </optgroup>" +
        "<optgroup label='冷却' class='group-7'><option value='7-1'>I 系</option><option value='7-2'>II系</option> </optgroup>" +
        "<optgroup label='制动' class='group-8'><option value='8-1'>制动</option> </optgroup>" +
        "<optgroup label='隔离' class='group-9'><option value='9-1'>隔离</option> </optgroup>" +
        "</select>";
	}else if(id==1&&(type==15||type==17||type==19||type==21)){
		str+="<select class='multipleSelect' multiple='multiple'><option value='1'>A机</option><option value='2'>B机</option></select>";
	}else{
		str+="<div style='width:100px'></div>";
	}
	return str+='</div>';
}
// 将查询到的下拉内容组合放到对应的位置
function ajaxOption(content){
	var str="<option value=''></option>";
	if(content!=""&&content!=null){
		for(var i=0;i<content.length;i++){
			str+="<option value="+content[i].VERSION_ID+">"+content[i].VERSION_NAME+"</option>";
		};
	}
	return str;
}
// 更换选中软件的版本信息，返回换装结果
function versionChange(){
	var changeObjs = [];
	// 根据软件id获取当前选中的文件id和换装位置信息并进行封装
	if(softIds.length>0){
		for(var i=0;i<softIds.length;i++){
			var changeObj = {};
			var softId = softIds[i];
			var fileObj = $("#"+softId+" select.signSelect");
			var fileId = "";
			if(fileObj.length>0){
				fileId = fileObj[0].value;
				changeObj.fileId = fileId;
				changeObj.softId = softId;
			}
			if(fileId!=""){// 如果选择要更换的文件则查询当前选中的换装位置
				var softChangePosition = "";
				var softChangePositionObj = [];
				var selectdOption = $("#"+softId+" select.multipleSelect");
				if(selectdOption.length>0){
					softChangePositionObj = selectdOption[0].selectedOptions;
				}
				if(selectdOption[0].length>0){
					for(var j=0;j<selectdOption[0].length;j++){
						if(selectdOption[0][j].selected){
							softChangePosition+="1";
						}else{
							softChangePosition+="0";
						}
					}
				}else{
					softChangePosition = "0";
				}
				changeObj.position=softChangePosition;// 换装位置可为空
				changeObjs.push(changeObj);
			}
		}
		var versionChanges = {id:selectPlatformId,softwares:changeObjs};
		//console.log(versionChanges);
		var a = JSON.stringify(versionChanges);
		if(window.WebSocket){
			// 初始化websocket链接，并发送数据，如果链接成功则将下拉框以及按钮置为不可用状态
			versionChangeWebSocket = new WebSocket('ws://'+ip+'/asts/versionChange');
			
			versionChangeWebSocket.onmessage = function(event) {
				getAllDataWebSocketMessageVersion(event);
			};
			
			versionChangeWebSocket.onerror = function(event) {
				  console.log('websocket链接异常');
				  versionChangeWebSocket.close();
			};
			versionChangeWebSocket.onopen = function(event) {
				// websocket打开后发送信息
				versionChangeWebSocket.send(a);
				changeDisable(true);
			};
			versionChangeWebSocket.onclose = function(event){
				changeDisable(false);
			};
	    }else{
	        console.log('This browser does not supports WebSocket');
	    }
		
	}	
}
count2 = 0;
function getAllDataWebSocketMessageVersion(event){
	var data = JSON.parse(event.data);// 获取到后台推送过来的数据
	if(data.end=="1"){
		versionChangeWebSocket.close("3111", "正常结束关闭链接");
	}else if(data.end=="2"){
		versionChangeWebSocket.close("3222", "发现异常结束关闭链接");
	}
 if(data.end=="0"||data.end=="1"){
		var id = data.softId;// 更换的软件id
		var num1 = data.succesSize;// 已成功更新软件个数
		var num2 = data.softwareSize;// 更换软件的总个数
		var result = data.result;// 更换结果
		$("#changeProgress")[0].innerHTML ="换装成功数/换装总数:"+num1+"/"+num2;
		if(result){
			$("#"+id).css("color","#00FF00");
		}else{
			$("#"+id).css("color","#FF0000");
		}
	}
};

// 当开始换装时将右侧所有输入框置为不可用状态，之后还原为可用状态
function changeDisable(disable){
	if(disable){
		$('.multipleSelect').multiselect('disable');
	}else{
		$('.multipleSelect').multiselect('enable');
	}
	$("select.signSelect").prop("disabled", disable);
	$("#changeBtn").prop("disabled", disable);
	// $("#reset").prop("disabled", disable);
}

// 终止测试或者请求测试返回异常信息的话都要把平台状态置为0
/**
 * post请求 * 修改平台状态信息 *
 * 
 * @param platformId *
 * @param status
 *            1自动；0结束用；2手动；3仿真 *
 */
function resetPlatformEdit(platformId){
	// 当当前任务为回访时，不对平台做处理
	if(currentTaskCompleteBool){
		return;
	}
	$.ajax({
		url: '../../../autoTest/updatePlatformStatus',
		type: 'POST',
		data: {
			platformId: platformId,// 平台id
			status: 0//
		},
		success: function (data) {
			//console.log(platformId);
			//console.log(data);
		}
	});
}

// 获取查看版本信息
function checkVersionBool(){
	for(var i = 0;i<allSequenceArray.length;i++){
		$.ajax({
			url: '../../../SoftwareVersionChange/getSoftwareVersion',
			type: 'POST',
			data: {
				id:allSequenceArray[i][0].PLATFORM_ID// 平台id
			},
			success: function (data) {
				//console.log(data);
				if(data.flag == 0){// 获取版本号信息成功，则弹出版本号信息界面
					showVersion();
					$('#startCHHF').html("开始测试");
				}else{
					danger("<div style='color:black'>"+data.errorInfo+"</div>");
				}
			},error:function(error){
				danger("<div style='color:black'>获取版本信息失败！</div>");
			}
		});
	}
}
// 修改测试任务状态信息 0未开始1进行中2完成3异常结束
function setTaskState(status){
	$.ajax({
		url: '../../../autoTest/updateTaskInfo',
		type: "POST",
		data: {
			taskId: testTaskId,
			status: status
		},
		success: function (data) {
			//改变任务状态成功后，记录下当前状态
			currentTaskState = status;
		},error:function(){
			
		}
	});
}

// 获取系统时间
function getSystemTime(callback){
	$.ajax({
		type:'POST',
		url:'../../../user/getSystemTime',
		data:{
			'type':1
		},success:function(data){
			callback(data.content);
		},error:function(error){
		}
	});
}

// 时间格式转时间戳
function timeToTimestamp(time){
	var date1 = new Date(time);
	return date1.getTime();
}
// 获取系统当前时间戳
function systemTimestamp(){
	return timeToTimestamp(getSystemTime());
}

// 时间戳转换为时间格式2018-05-03 14:00:00
function timestampToTime(timestamp) {
    var date = new Date(timestamp);// 时间戳为10位需*1000，时间戳为13位的话不需乘1000
    Y = date.getFullYear() + '-';
    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    D = (date.getDate() < 10 ? '0'+(date.getDate()) : date.getDate()) + " ";
    h = (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours()) + ":";
    m = (date.getMinutes() < 10 ? '0'+(date.getMinutes()) : date.getMinutes()) + ":";
    s = (date.getSeconds() < 10 ? '0'+(date.getSeconds()) : date.getSeconds()) + ".";
    ms = date.getMilliseconds();
    return Y+M+D+h+m+s+ms;
}

// 日志显示出来，time:时间，log:日志内容
function addAutoLog(time,log) {
	if(!log){
		return;
	}
	//不显示空提示信息
	if(log == ": "||log.indexOf("ASTS_SetElementID")>=0){
		return;
	}
	var content = '';
	//根据日志类型显示不同的颜色：TRUE:green,FALSE:red,其他：white
	var a = log.split(":")[0];
	var color = "white";
	if(a=="TRUE"){
		color="green";
	}else if(a=="FALSE"){
		color="red";
	}
	content = "<div class='manualLogCell'><div class='logLeft'>" +
		time +
		"</div><div class='logRight' style='color:"+color+"'><div><span>" + log +
		"</span></div><div></div></div></div>";
	$("#testLogs").append(content);
	$("#testLogs").scrollTop(999999999);
}

// 设置caseElements数据中的空间大小和位置
function setDrawSize(obj) {
	// 设置控件的大小
	setCaseSize(obj);
	// 设置控件的位置
	setCaseArray(caseElements);
}
// 设置控件的大小
function setCaseSize(obj) {
	var size = new Object;
	var heightCount = 0;
	var widthCount = 0;
	if (obj.leve == '1') {
		heightCount = heightCount + rectHeight;
		widthCount = rectWidth;
	} else if (obj.leve == '2') {
		heightCount = heightCount + banchLoopTitleHeight;
		var widthLeft = 0;
		var widthRight = 0;
		if (obj.type == '015') {
			var leftHeight = betweenTool;
			var rightHeight = betweenTool;
			for (var p = 0; p < obj.leftChildrens.length; p++) {
				var returnSize = setCaseSize(obj.leftChildrens[p]);
				leftHeight = leftHeight + returnSize.height;
				if (!obj.leftChildrens[p].width) {
					obj.leftChildrens[p].width = getWidth(obj.leftChildrens[p]);
				}
				if (widthLeft < returnSize.width) {
					widthLeft = returnSize.width;
				}
			}
			for (var q = 0; q < obj.rightChildrens.length; q++) {
				var returnSize = setCaseSize(obj.rightChildrens[q]);
				rightHeight = rightHeight + returnSize.height;
				if (!obj.rightChildrens[q].width) {
					obj.rightChildrens[q].width = getWidth(obj.rightChildrens[q]);
				}
				if (widthRight < returnSize.width) {
					widthRight = returnSize.width;
				}
			}
			if (leftHeight >= rightHeight) {
				heightCount = heightCount + leftHeight;
			} else {
				heightCount = heightCount + rightHeight;
			}
			if (widthLeft < banchLoopWidth) {
				widthLeft = banchLoopWidth;
			}
			if (widthRight < banchLoopWidth) {
				widthRight = banchLoopWidth;
			}
			widthCount = widthLeft + widthRight;
			obj.leftWidth = widthLeft;
			obj.rightWidth = widthRight;
		} else if (obj.type == '016') {
			heightCount = heightCount + betweenTool;
			for (var i = 0; i < obj.childrens.length; i++) {
				var returnSize = setCaseSize(obj.childrens[i]);
				heightCount = heightCount + returnSize.height;
				if (!obj.childrens[i].width) {
					obj.childrens[i].width = getWidth(obj.childrens[i]);
				}
				if (widthCount < returnSize.width) {
					widthCount = returnSize.width;
				}
			}
			if (widthCount < banchLoopWidth) {
				widthCount = banchLoopWidth;
			}
		}
	}
	obj.height = heightCount;
	obj.width = widthCount;
	size.height = heightCount + betweenTool;
	size.width = widthCount + betweenTool + betweenTool;
	return size;
}
// 设置控件的位置
function setCaseArray(objArray) {
	var MARGIN = betweenTool;
	var x = initLocation.x;
	var y = initLocation.y;
	for (var i = 0; i < objArray.length; i++) {
		var size = setCasePostion(objArray[i], x, y);
		y = y + size.cy + MARGIN;
	}
}
// 设置控件的位置
function setCasePostion(obj, X, Y) {
	var MARGIN = betweenTool;
	var returnSize = new Object;
	returnSize.cx = 0;
	returnSize.cy = 0;
	obj.x = X;
	obj.y = Y;
	if (obj.leve == '1') {
		returnSize.cx = rectWidth;
		returnSize.cy = rectHeight;
	} else if (obj.leve == '2') {
		if (obj.type == '015') {
			var xMaxLeft = 0;
			var yLeft = Y + banchLoopTitleHeight + MARGIN;
			if (obj.leftChildrens.length <= 0) {
				xMaxLeft = banchLoopWidth;
			}
			for (var i = 0; i < obj.leftChildrens.length; i++) {
				var size = setCasePostion(obj.leftChildrens[i], X + MARGIN,
						yLeft);
				yLeft = yLeft + size.cy + MARGIN;
				if (xMaxLeft < MARGIN + size.cx + MARGIN)
					xMaxLeft = MARGIN + size.cx + MARGIN;
			}
			var xMaxRight = 0;
			if (obj.rightChildrens.length <= 0) {
				xMaxRight = banchLoopWidth;
			}
			var yRight = Y + banchLoopTitleHeight + MARGIN;
			for (var i = 0; i < obj.rightChildrens.length; i++) {
				var size = setCasePostion(obj.rightChildrens[i], X + xMaxLeft
						+ MARGIN, yRight);
				yRight = yRight + size.cy + MARGIN;
				if (xMaxRight < MARGIN + size.cx + MARGIN)
					xMaxRight = MARGIN + size.cx + MARGIN;
			}
			returnSize.cx = xMaxLeft + xMaxRight;
			returnSize.cy = (yLeft > yRight ? yLeft : yRight) - Y;
		} else if (obj.type == '016') {
			returnSize.cx = banchLoopWidth;
			returnSize.cy = banchLoopTitleHeight + MARGIN;
			var y = Y + banchLoopTitleHeight + MARGIN;
			for (var i = 0; i < obj.childrens.length; i++) {
				var size = setCasePostion(obj.childrens[i], X + MARGIN, y);
				y = y + size.cy + MARGIN;
				if (returnSize.cx < MARGIN + size.cx + MARGIN)
					returnSize.cx = MARGIN + size.cx + MARGIN;
			}
			returnSize.cy = y - Y;
		}
	}
	return returnSize;
}
// 获取空间的初始大小
function getWidth(obj) {
	var w = 0;
	if (obj.leve == '1') {// 小矩形控件
		w = rectWidth;
	} else {
		if (obj.type == '015') {// 分支
			w = banchLoopWidth * 2;
		} else if (obj.type == '016') {// 循环
			w = banchLoopWidth;
		}
	}
	return w;
}
// 画布高度根据增删改查控件后可以自适应
function resetCanvasHeight(){
	if (caseElements.length > 0) {
		if(caseElements[caseElements.length - 1] && caseElements[caseElements.length - 1].y){
			if((caseElements[caseElements.length - 1].y + caseElements[caseElements.length - 1].height)+150 > 750){
				canvas.height = caseElements[caseElements.length - 1].y
				+ caseElements[caseElements.length - 1].height + 150;
			}
		}else if(caseElements[caseElements.length - 2] && caseElements[caseElements.length - 2].y){
			if((caseElements[caseElements.length - 2].y + caseElements[caseElements.length - 2].height)+150 > 750){
				canvas.height = caseElements[caseElements.length - 2].y
				+ caseElements[caseElements.length - 2].height + 150;
			}
		}
	}
}

// 绘制图形
function drawProcessChart(caseElements) {
	for (var i = 0; i < caseElements.length; i++) {
		if (caseElements[i].leve == '1') {// 控件
			var diagonal = autoTDrawCanvas.getDrawing('diagonal', {
				obj : {
					text : caseElements[i].name,
					x : caseElements[i].x,
					y : caseElements[i].y,
					color : '#7F7F7F',
					width : rectWidth,
					height : rectHeight,
					selected : caseElements[i].selected,
					stateType:caseElements[i].stateType,
					viewType:1
				}
			});
			diagonal.draw();
		} else if (caseElements[i].leve == '2') {// 分支或者循环
			if (caseElements[i].type == '015') {// 分支
				var coditionCount = 0;
				if(caseElements[i].conditionList){
					coditionCount = caseElements[i].conditionList.length;
				}
				var branchCell = autoTDrawCanvas.getDrawing('branch', {
					x : caseElements[i].x,
					y : caseElements[i].y,
					width : caseElements[i].width,
					height : caseElements[i].height,
					bottomLeftWidth : caseElements[i].leftWidth,
					bottomRightWidth : caseElements[i].rightWidth,
					filledColor : titleBackGround,
					selected : caseElements[i].selected,
					conditionPostion:conditionPostion,
					conditionSpace:conditionSpace,
					conditionCount:coditionCount,
					conditionList:caseElements[i].conditionList,
					stateType:caseElements[i].stateType
				});
				branchCell.draw();
				drawProcessChart(caseElements[i].leftChildrens);
				drawProcessChart(caseElements[i].rightChildrens);
			} else if (caseElements[i].type == '016') {// 循环
				var coditionCount = 0;
				if(caseElements[i].conditionList){
					coditionCount = caseElements[i].conditionList.length;
				}
				var loopCell = autoTDrawCanvas.getDrawing('loop', {
					x : caseElements[i].x,
					y : caseElements[i].y,
					width : caseElements[i].width,
					height : caseElements[i].height,
					isLabel : false,
					filledColor : titleBackGround,
					selected : caseElements[i].selected,
					conditionPostion:conditionPostion,
					conditionSpace:conditionSpace,
					conditionCount:coditionCount,
					conditionList:caseElements[i].conditionList,
					stateType:caseElements[i].stateType
				});
				loopCell.draw();
				drawProcessChart(caseElements[i].childrens);
			}
		} else if (caseElements[i].leve == '3') {// 条件轴

		}
	}
}
// 重置caseElements中控件的selected为false，为不选中状态
function resetSelected() {
	for (var i = 0; i < caseElements.length; i++) {
		loopReSetSelected(caseElements[i]);
	}
}
// 递归重置caseElements中控件的selected为false，为不选中状态
function loopReSetSelected(obj) {
	obj.selected = false;
	if (obj.leve == '1') {
	} else if (obj.leve == '2') {
		for(var i = 0;i<obj.conditionList.length;i++){
			obj.conditionList[i].selected = false;
		}
		if (obj.type == '015') {
			for (var i = 0; i < obj.leftChildrens.length; i++) {
				loopReSetSelected(obj.leftChildrens[i]);
			}
			for (var i = 0; i < obj.rightChildrens.length; i++) {
				loopReSetSelected(obj.rightChildrens[i]);
			}
		} else if (obj.type == '016') {
			for (var i = 0; i < obj.childrens.length; i++) {
				loopReSetSelected(obj.childrens[i]);
			}
		}
	}
}

//如果当时任务没有测试过，不是回放，那么给结束时间修改为预期结束时间，一个序列为5分钟
function setExpectTime(timeStr){
	$('#testEndLebal').text("预期结束时间：");
	var date = new Date(timeStr);
	var min = date.getMinutes();
	date.setMinutes(min+5*currentSequenceList.length);
	$('#testEndTime').text(timestampToTime(date.getTime()));
}